package com.ztom.offer.v2;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 从尾到头打印链表
 * <p>
 * https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
 *
 * @author ZhangTao
 */
public class Code04ReversePrint {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public int[] reversePrint1(ListNode head) {
        if (head == null) {
            return new int[]{};
        }

        Deque<ListNode> stack = new LinkedList<>();
        ListNode node = head;
        while (node != null) {
            stack.offerLast(node);
            node = node.next;
        }
        int size = stack.size();
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[i] = stack.pollLast().val;
        }
        return res;
    }

    public int[] reversePrint(ListNode head) {
        if (head == null) {
            return new int[]{};
        }

        int size = 0;
        ListNode node = head;
        while (node != null) {
            size++;
            node = node.next;
        }
        int[] res = new int[size];
        node = head;
        for (int i = size - 1; i >= 0; i--) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }
}
